package com.why.cachecloud.service.task.util;

import com.why.cachecloud.service.custom.alert.DingTalkComponent;
import com.why.cachecloud.dao.MachineRoomDao;
import com.why.cachecloud.entity.AppAudit;
import com.why.cachecloud.entity.AppDesc;
import com.why.cachecloud.entity.AppUser;
import com.why.cachecloud.service.stats.app.AppStatsCenter;
import com.why.cachecloud.util.ConstUtils;
import com.why.cachecloud.util.EnvUtil;
import com.why.cachecloud.web.service.AppService;
import com.why.cachecloud.web.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * 微信通知
 */
@Component
public class AppDingTalk {

    private final Logger logger = LoggerFactory.getLogger(AppDingTalk.class);

    @Autowired(required = false)
    private DingTalkComponent dingTalkComponent;

    @Autowired
    private UserService userService;

    @Autowired
    private MachineRoomDao machineRoomDao;

    @Autowired
    private AppService appService;

    @Autowired
    private AppStatsCenter appStatsCenter;
    @Autowired
    private Environment environment;

    /**
     * 应用状态通知
     *
     * @param appDesc
     * @param appAudit
     */
    public void noticeAppResult(AppDesc appDesc, AppAudit appAudit) {
        if (EnvUtil.isDev(environment)) {
            return;
        }
        try {
            long userId = appDesc.getUserId();
            AppUser appUser = userService.get(userId);

            long applyUserId = appAudit.getUserId();
            AppUser applyAppUser = userService.get(applyUserId);

            StringBuilder appCreateContent = new StringBuilder();
            appCreateContent.append("#### 应用申请通知 @").append(appUser.getMobile()).append("@").append(applyAppUser.getMobile()).append(" \n\n");
            appCreateContent.append(String.format("申请类型: %s \n\n", appAudit.getTypeDesc()));
            appCreateContent.append(String.format("申请描述: %s \n\n", appAudit.getInfo()));
            appCreateContent.append(String.format("申请时间: %s \n\n", appAudit.getCreateTimeFormat()));
            appCreateContent.append(String.format("申请人员: %s \n\n", applyAppUser.getChName()));
            appCreateContent.append(String.format("申请状态: %s \n\n", appAudit.getStatusDesc()));
            appCreateContent.append(String.format("集群名称: %s \n\n", appDesc.getName()));
            if (StringUtils.isNotBlank(appAudit.getRefuseReason())) {
                appCreateContent.append(String.format("处理描述: %s \n\n", appAudit.getRefuseReason()));
            }
            Set<String> phoneList = new HashSet<>();
            phoneList.add(appUser.getMobile());
            phoneList.add(applyAppUser.getMobile());

            dingTalkComponent.sendDingTalk(appCreateContent.toString(), new ArrayList<>(phoneList));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 集群认领
     *
     * @param appDesc
     * @param operateUser
     */
    public void noticeAppClaim(AppDesc appDesc, AppUser operateUser) {
        if (EnvUtil.isDev(environment)) {
            return;
        }

        try {
            StringBuffer appCreateContent = new StringBuffer();
            appCreateContent.append("#### 集群认领通知 @"+ operateUser.getMobile() +" \n\n");
            appCreateContent.append(String.format("> 事件类型: %s \n\n", "集群认领"));
            appCreateContent.append(String.format("> 认领人员: %s", operateUser.getChName()));
            appCreateContent.append(String.format("> 认领时间: %s \n\n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
            appCreateContent.append(String.format("> 集群名称: %s \n\n", appDesc.getName()));
            Set<String> set = new HashSet<>();
            set.add(operateUser.getMobile());
            dingTalkComponent.sendDingTalk(appCreateContent.toString(), new ArrayList<>(set));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public void noticeRmtSyncFinish(long sourceAppId, long targetAppId) {
        if (EnvUtil.isDev(environment)) {
            return;
        }
        try {
            AppDesc sourceAppDesc = appService.getByAppId(sourceAppId);
            AppDesc targetAppDesc = appService.getByAppId(targetAppId);

            String content = "#### 扩容同步完成通知 "+ ConstUtils.getPhoneString() +" \n\n" +
                    String.format("源集群 : %s \n\n", sourceAppDesc.getName()) +
                    String.format("目集群 : %s \n\n", targetAppDesc.getName()) +
                    "可以执行redis.sh --update";
            dingTalkComponent.sendDingTalkToAdmin(content);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public void noticeTaskAbort(long taskId, String stepName) {
        if (EnvUtil.isDev(environment)) {
            return;
        }
        try {
            String content = "#### 任务中断通知 "+ ConstUtils.getPhoneString() +" \n\n" +
                    String.format("任务id=%s,stepName=%s中断，请查看", taskId, stepName);
            dingTalkComponent.sendDingTalkToAdmin(content);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public void noticeAppScaleStop(long sourceAppId, long targetAppId) {
        if (EnvUtil.isDev(environment)) {
            return;
        }
        try {
            AppDesc sourceAppDesc = appService.getByAppId(sourceAppId);
            AppDesc targetAppDesc = appService.getByAppId(targetAppId);
            dingTalkComponent.sendDingTalkToAdmin(String.format("#### 集群缩容通知 "+ ConstUtils.getPhoneString() +" \n\n 集群%s->%s的rmt被强制中断,请查看cc任务日志", sourceAppDesc.getName(), targetAppDesc.getName()));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public void noticeRmtUseMaster(long sourceAppId, long targetAppId) {
        if (EnvUtil.isDev(environment)) {
            return;
        }
        try {
            String content = "#### 集群迁移通知 "+ ConstUtils.getPhoneString() +" \n\n" +
                    String.format("集群迁移%s->%s，使用了master做source", sourceAppId, targetAppId);
            dingTalkComponent.sendDingTalkToAdmin(content);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 野生实例
     *
     * @param ip
     * @param port
     */
    public void noticeWildInstance(String ip, int port) {
        if (EnvUtil.isDev(environment)) {
            return;
        }
        try {
            String content = "#### 野生实例通知 "+ ConstUtils.getPhoneString() +" \n\n" +
                    String.format("野生实例 %s:%s is not in instance_info", ip, port);
            dingTalkComponent.sendDingTalkToAdmin(content);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

}
